package com.colbby.datahouse.mapper;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Map;

import com.colbby.datahouse.transform.DataTypeTransform;
import com.colbby.datahouse.transform.ObjectTransformer;
import com.colbby.datahouse.utils.TypeDescriptor;

public class Converter {

	public static <T> T convert(Map<String, Object> map, Class<T> clazz, PropertyMapping mapping) {
		T object = newInstance(clazz);
		DataTypeTransform<?> tran = ObjectTransformer.getDirectedTransformer();
		try {
			PropertyDescriptor[] ps = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
			for(PropertyDescriptor p : ps) {
				if("class".equals(p.getName())) continue;
				Method setter = p.getWriteMethod();
				if(setter == null) continue;
				String mapProName = mapping.mapping(p.getName());
				Object value = map.get(mapProName);
				Class<?> requiredType = p.getPropertyType();
				value = tran.transform(new TypeDescriptor(requiredType), value);
				setter.invoke(object, value);
			}
			return object;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	private static <T> T newInstance(Class<T> clazz) {
		try {
			return clazz.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
}